package com.heima.wemedia.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.file.service.impl.MinIOFileStorageServiceImpl;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.util.WmThreadLocal;
import org.bouncycastle.math.ec.WNafL2RMultiplier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Resource
    private FileStorageService fileStorageService;
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    @Transactional
    public WmMaterial upload(MultipartFile file) {
        WmMaterial wmMaterial = new WmMaterial();
        try {
            String filename = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            String uploadImgFile = fileStorageService.uploadImgFile("", filename, inputStream);
            if (StrUtil.isNotEmpty(uploadImgFile)) {
                WmUser user = WmThreadLocal.getUser();
                wmMaterial.setUserId(user.getId());
                wmMaterial.setUrl(uploadImgFile);
                wmMaterial.setType(Convert.toShort(0));
                wmMaterial.setIsCollection(Convert.toShort(0));
                wmMaterial.setCreatedTime(new Date());
                save(wmMaterial);
            }
        } catch (IOException e) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        return wmMaterial;
    }

    @Override
    public PageResponseResult<List<WmMaterial>> selectByPage(WmMaterialDto wmMaterialDto) {
        Page<WmMaterial> p = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());

        Page<WmMaterial> page = lambdaQuery()
                .eq(wmMaterialDto.getIsCollection() != null, WmMaterial::getIsCollection, wmMaterialDto.getIsCollection())
                .eq(WmMaterial::getUserId, WmThreadLocal.getUser().getId())
                .orderByDesc(WmMaterial::getCreatedTime)
                .page(p);

        return PageResponseResult.<List<WmMaterial>>builder()
                .total(Convert.toInt(page.getTotal()))
                .size(wmMaterialDto.getSize())
                .currentPage(wmMaterialDto.getPage())
                .data(page.getRecords())
                .build();
    }

    @Override
    public ResponseResult<Object> delImage(Integer id) {
        if (ObjectUtil.isEmpty(id)){
            return ResponseResult.errorResult(501, "参数失效");
        }

        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(new QueryWrapper<WmNewsMaterial>().eq("material_id", id));
        if (ObjectUtil.isEmpty(wmNewsMaterials)){
            WmMaterial wmMaterial = getById(id);
            if (ObjectUtil.isEmpty(wmMaterial)){
                return ResponseResult.errorResult(1002,"数据不存在");
            }
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(501, "文件删除失败");
    }

    @Override
    public ResponseResult<Object> concelCollect(Integer id) {
        WmMaterial wmMaterial = this.getById(id);
        if (ObjectUtil.isNotEmpty(wmMaterial) && ObjectUtil.equals(wmMaterial.getIsCollection(), Convert.toShort(1))){
            wmMaterial.setIsCollection(Convert.toShort(0));
            updateById(wmMaterial);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    @Override
    public ResponseResult<Object> collect(Integer id) {
        WmMaterial wmMaterial = this.getById(id);
        if (ObjectUtil.isNotEmpty(wmMaterial) && ObjectUtil.equals(wmMaterial.getIsCollection(), Convert.toShort(0))){
            wmMaterial.setIsCollection(Convert.toShort(1));
            updateById(wmMaterial);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
